package com.dc.schedule.client.sample;

import com.dc.schedule.client.context.ClientExecutionContextManager;
import com.dc.schedule.client.context.ClientTaskExecutionContext;
import com.dc.schedule.spring.anno.StaticTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 调度任务示例使用方法
 */
@Service
@Slf4j
public class StaticTaskService {
    
    private final ClientExecutionContextManager clientExecutionContextManager = ClientExecutionContextManager.getINSTANCE();
    
    // expression 配置错误, 任务默认不会执行
    @StaticTask(expression = "")
    public void task1() {
        // 无参的任务, 可以通过 ClientExecutionContextManager 获取任务执行信息
        ClientTaskExecutionContext context = clientExecutionContextManager.getCurrentExecutionContext();
        log.info("这里是任务1.{}...", context);
        context.setResultMessage("任务1 于 %s 执行成功".formatted(LocalDateTime.now()));
    }
    
    // 带一个ClientTaskExecutionContext参数, 可以自动注入
    @StaticTask(expression = "0/10 * * * * ?")
    public void task2(ClientTaskExecutionContext context) {
        log.info("这里是任务2.{}...", context);
        context.setResultMessage("任务2 于 %s 执行成功".formatted(LocalDateTime.now()));
    }
    
    // 有返回值, 返回值会记录在执行结果里
    @StaticTask(expression = "0/10 * * * * ?")
    public String task3(ClientTaskExecutionContext context) {
        log.info("这里是任务3.{}...", context);
        return "任务3 于 %s 执行成功".formatted(LocalDateTime.now());
    }
    
    @StaticTask(expression = "5/10 * * * * ?")
    public String task4(ClientTaskExecutionContext context) {
        log.info("这里是任务4.{}...", context);
        throw new IllegalStateException("如果任务抛出异常, 将会标记任务失败, 并且记录在执行记录里面");
    }
    
    // 测试任务执行时间大于调度间隔
    @StaticTask(expression = "0/5 * * * * ?")
    public Object task5(ClientTaskExecutionContext context) throws InterruptedException {
        log.info("这里是任务5开始.{}...", context);
        Thread.sleep(10000L);
        log.info("这里是任务5结束...");
        return context;
    }
    
}
